package com.eqxiu.ieditor.homepage.controller;

import com.eqxiu.common.persistence.Page;
import com.eqxiu.ieditor.api.HomePageSceneServiceApi;
import com.eqxiu.ieditor.api.HomePageUserServiceApi;
import com.eqxiu.ieditor.api.controller.BaseApiController;
import com.eqxiu.ieditor.commons.web.ResultData;
import com.eqxiu.ieditor.dto.HomePageBaseInfoDTO;
import com.eqxiu.ieditor.dto.HomePageUserSceneDTO;
import com.eqxiu.mall.marketing.api.MarketComponentSceneRelApi;
import com.eqxiu.scene.api.BaseSceneServiceApi;
import com.eqxiu.scene.dto.SceneDTO;
import com.eqxiu.scene.dto.SceneParam;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @ClassName HomePageSceneController
 * @escription 微主页作品入口
 * @Author suixiangyu
 * @Date 2019/4/311:20 AM
 */
@Controller
@Api(description = "微主页作品信息入口")
public class HomePageSceneController implements BaseApiController {

    private final Logger LOGGER = LoggerFactory.getLogger(HomePageSceneController.class);

    private final String HOMEPAGE_SCENE_STATUS_ON = "1";
    private final String HOMEPAGE_SCENE_STATUS_OFF = "0";
    @Autowired
    private HomePageSceneServiceApi homePageSceneServiceApi;

    @Autowired
    private HomePageUserServiceApi homePageUserServiceApi;


    @Autowired
    private BaseSceneServiceApi baseSceneServiceApi;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MarketComponentSceneRelApi marketComponentSceneRelApi;


    /**
     * @return com.eqxiu.ieditor.commons.web.ResultData
     * @Description 分页获取用户场景
     * @Author SuiXiangyu
     * @Date 2019/4/3
     * @Param [userId, pageNo, pageSize]
     **/
    @PostMapping("api/homepage/get-user-scene")
    @ResponseBody
    @ApiOperation(value = "分页获取用户场景 userid必传")
    public ResultData getUserScene(String userId, int pageNo, int pageSize) {
        if ("".equals(userId)) {
            return fail().setMsg("userid can not be null");
        }
        try {
            SceneParam sceneParam = new SceneParam();
            sceneParam.setUser(userId);
            sceneParam.setPageNo(pageNo);
            sceneParam.setPageSize(pageSize);
            //分页查询用户名下已发布状态场景
            Page<SceneDTO> newSceneListPage = baseSceneServiceApi.findSceneListBySceneParamForPc(sceneParam);
            List<SceneDTO> sceneDTOs = newSceneListPage.getList();
            //设置property值，h5编辑器数据分散在oracle和mysql，所以分开取
            for (SceneDTO sceneDTO : sceneDTOs) {
                Long id = sceneDTO.getId();
                Map<String, Object> show = new HashMap<>(16);
                int i = homePageSceneServiceApi.countHomePageBySceneId(Integer.valueOf(String.valueOf(id)));
                if (i>0){
                    show.put("show",false);
                    sceneDTO.setProperty(new Gson().toJson(show));
                }else {
                    show.put("show",true);
                    sceneDTO.setProperty(new Gson().toJson(show));
                }
            }
            newSceneListPage.setPageSize(pageSize);
            return success().setObj(newSceneListPage);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return success().setObj(null);
        }
    }

    /**
     * @return com.eqxiu.ieditor.commons.web.ResultData
     * @Description 分页查询微主页用户作品
     * @Author SuiXiangyu
     * @Date 2019/4/3
     * @Param [userId, pageNo, pageSize]
     **/
    @PostMapping("api/homepage/homepage-user-scene")
    @ResponseBody
    @ApiOperation(value = "分页查询微主页用户作品")
    public ResultData getHomePageScene(String userId, int pageNo, int pageSize, boolean orderByTime, boolean orderBySort) {
        try {
            Map<String, Object> stringObjectMap = homePageSceneServiceApi.queryHomePageByUserId(userId, pageNo, pageSize, orderByTime, orderBySort);
            return success().setMap(stringObjectMap);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return fail();
        }
    }

    /**
     * 查询头像组件位置接口
     *
     * @param sceneCode 场景code
     * @return ResultData
     **/
    @GetMapping("api/homepage/homepage-base-info")
    @ResponseBody
    @ApiOperation(value = "查询头像组件位置接口")
    public ResultData getHomePageBaseInfo(String sceneCode) {
        if (StringUtils.isBlank(sceneCode)) {
            LOGGER.error("场景code为空！");
            return fail().setMsg("场景code为空");
        }

        HomePageBaseInfoDTO homePageBaseInfoDTO = homePageSceneServiceApi.getHomePageBaseInfo(sceneCode);
        if (null == homePageBaseInfoDTO) {
            return fail().setMsg("未查询到微主页的头像组件等基础信息！");
        }
        return success().setObj(homePageBaseInfoDTO);
    }


    /**
     * @return com.eqxiu.ieditor.commons.web.ResultData
     * @Description 添加微主页作品
     * @update 添加微主页作品不再通知编辑器
     * @Author SuiXiangyu
     * @Date 2019/4/3
     * @Param [homePageSceneList]
     **/
    @PostMapping("api/homepage/save-scene")
    @ResponseBody
    @ApiOperation(value = "添加微主页作品")
    public ResultData addHomePageScene(@RequestBody ArrayList<HomePageUserSceneDTO> homePageSceneList) {
        List<HomePageUserSceneDTO> newHomePageUserSceneDTOS = new ArrayList<HomePageUserSceneDTO>();
        String userId = null;
        //处理作品信息
        try {
            if (homePageSceneList != null && homePageSceneList.size() > 0) {
                userId = homePageSceneList.get(0).getUserId();
                for (HomePageUserSceneDTO homePageUserSceneDTO : homePageSceneList) {
                    homePageUserSceneDTO.setCreateTime(new Date());
                    homePageUserSceneDTO.setUpdateTime(new Date());
                    homePageUserSceneDTO.setSort(1000);
                    newHomePageUserSceneDTOS.add(homePageUserSceneDTO);
                    //通知编辑器开启场景微主页设置状态
                    //applicationEventPublisher.publishEvent(new HandleSceneStatusEvent(String.valueOf(homePageUserSceneDTO.getUserId()), String.valueOf(homePageUserSceneDTO.getSceneId()), HOMEPAGE_SCENE_STATUS_ON, true));
                }
                homePageSceneServiceApi.addHomePageScene(homePageSceneList);
            }
            return success();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return fail();
        }
    }

    /**
     * @return com.eqxiu.ieditor.commons.web.ResultData
     * @Description 根据场景id移除作品
     * @Author SuiXiangyu
     * @Date 2019/4/3
     * @Param [sceneId]
     **/
    @PostMapping("api/homepage/remove-homepage-scene")
    @ResponseBody
    @ApiOperation(value = "根据场景id移除作品")
    public ResultData removeHomePageScene(String sceneId, String userId) {
        if (sceneId == null) {
            return fail().setMsg("scene id can not be null");
        }
        try {
            //删除作品表数据
            homePageSceneServiceApi.deleteHomePageScene(Integer.parseInt(sceneId));
            //通知编辑器关闭场景微主页设置状态
            //applicationEventPublisher.+ (new HandleSceneStatusEvent(userId, sceneId, HOMEPAGE_SCENE_STATUS_OFF, true));
            return success();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return fail();
        }
    }

    /**
     * @return com.eqxiu.ieditor.commons.web.ResultData
     * @Description 更新排序值
     * @Author SuiXiangyu
     * @Date 2019/4/3
     * @Param [userId, sceneId, sort]
     **/
    @PostMapping("api/homepage/scene-sort")
    @ResponseBody
    @ApiOperation(value = "更新排序值")
    public ResultData updateSceneSort(Integer homePageId, int sort, String userId) {
        try {
            HomePageUserSceneDTO homePageUserSceneDTO = new HomePageUserSceneDTO();
            homePageUserSceneDTO.setId(homePageId);
            homePageUserSceneDTO.setSort(sort);
            homePageUserSceneDTO.setUpdateTime(new Date());
            homePageSceneServiceApi.updateHomePageScene(homePageUserSceneDTO);
            return success();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return fail();
        }
    }


}
